package com.kymatrix.kycarbon.xsmd.common.tenant.filter;

import com.kymatrix.kycarbon.xsmd.common.tenant.context.TenantContextHolder;
import com.kymatrix.kycarbon.xsmd.common.util.ServletUtils;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

@Slf4j
public class TenantContextWebFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String tenantId = ServletUtils.getTenantId(request);
//        if (tenantId != null) {
            log.info("设置：从request中获取tenantId={}并设置到上下文中", tenantId);
        TenantContextHolder.setTenantId("1");
//            TenantContextHolder.setTenantId(tenantId);
//        }
        try {
            chain.doFilter(request, response);
        } finally {
            log.info("清理：从request中获取tenantId={}并设置到上下文中", tenantId);
            TenantContextHolder.clear();
        }
    }

}
